package cn.edu.zzuli.service;

import cn.edu.zzuli.entity.R;
import cn.edu.zzuli.entity.UserEntity;
import cn.edu.zzuli.mapper.UserEntityMapper;
import cn.edu.zzuli.util.AliOssUtils;
import cn.edu.zzuli.util.JwtUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserEntityService {

    @Resource
    UserEntityMapper userEntityMapper;

    @Resource
    AliOssUtils ossUtils;


    public R getUserByUserName(String username, String password) {

        UserEntity u = null;
        //select user
        if( (u = userEntityMapper.getUserByUserName(username) ) != null
                && password.equals(u.getPassword())){

            //获取授权连接
            String URL = ossUtils.getUrl(u.getAvater(),24 * 3600 * 1000).toString();
            u.setAvater(URL);
            //生成对应的 token
            String token = JwtUtil.sign(u.getUId().toString(),
                    u.getUsername(), System.currentTimeMillis());

            return R.success().add("token", token).add("user", u);
        }

        return R.error().appendMsg("用户名或者密码错误");
    }


    public UserEntity getUserById(Integer id) {
        UserEntity u = null;

        //TODO 从redis中 获取 用户缓存信息

        //redis 中没有的话，从数据库中获取 用户信息。
        if( (u = userEntityMapper.getUserById(id)) == null) {
            return null;
        }

        String URL = ossUtils.getUrl(u.getAvater()).toString();
        u.setAvater(URL);
        return u;
    }

    @Transactional
    public R aboutRegister(JSONObject jsonObject) {
        UserEntity u = null;
        if (( u = checkInfo(jsonObject)) == null) return null;

        //我们这里再校验一下手机号有没有重复。
        List<String> phonesInfo = userEntityMapper.getPhonesInfo();

        long phone = phonesInfo.stream()
                .filter(p -> p.equals(jsonObject.getString("phone"))).count();

        if (phone != 0) {
            return R.error().appendMsg("手机号重复了");
        }

        try {
            if (userEntityMapper.add(u)) {

                //顺便在这里登陆一下
                //生成对应的 token
                String token = JwtUtil.sign(u.getUId().toString(),
                        u.getUsername(), System.currentTimeMillis());
                return R.success().add("token", token).add("user", u);
            }
        } catch (Exception e) {
            return R.error().appendMsg("添加用户的时候，出错了");
        }

        return R.error();
    }

    private UserEntity checkInfo(JSONObject user) {
        UserEntity u = new UserEntity()
                .setUsername(user.getString("username"))
                .setPassword(user.getString("password"))
                .setPhone(user.getString("phone"))
                .setNickname(user.getString("nickname"));
        if (StringUtils.isEmpty(u.getUsername())
                || StringUtils.isEmpty(u.getPassword())
                || StringUtils.isEmpty(u.getNickname())
                || StringUtils.isEmpty(u.getPhone())) {
            return null;
        }

        if (StringUtils.isEmpty(user.getString("gender"))) {
            u.setGender("未知");
        }
        if (StringUtils.isEmpty(user.getString("avater"))) {
            u.setAvater("/ekij.jpg");
        }

        return u;
    }
}
